package com.goodsogood.union.auth.redis;

import com.goodsogood.union.auth.conf.LogConfiger;
import com.goodsogood.union.auth.conf.RedisConfiger;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * redis池
 */
@Component
public class RedisPool {
    
    static final Logger logger = LoggerFactory.getLogger(LogConfiger.APP);
    
    private static JedisPool pool;

    private static String HOST = RedisConfiger.getInstance().getAddr();
    private static String AUTH = RedisConfiger.getInstance().getPwd();
    private static int MAXIDEL = 200;
    private static int MAXTOTAL = 300;
    private static int PORT = 6379;
    private static int TIMEOUT = 3000;

    private void init(){
        JedisPoolConfig config = new JedisPoolConfig();
        //最大空闲连接数, 应用自己评估，不要超过ApsaraDB for Redis每个实例最大的连接数
        config.setMaxIdle(MAXIDEL);
        //最大连接数, 应用自己评估，不要超过ApsaraDB for Redis每个实例最大的连接数
        config.setMaxTotal(MAXTOTAL);
        config.setTestOnBorrow(false);
        config.setTestOnReturn(false);
        
        logger.info("redisPool' host is {}", HOST);
        pool = new JedisPool(config, HOST, PORT, TIMEOUT, AUTH);
    }

    public Jedis getResource() {
        if(pool==null){
            init();
        }
        return pool.getResource();
    }
    /**
     * 释放jedis资源
     * @param jedis
     */
    public void returnResource(final Jedis jedis) {
        if (jedis != null) {
            try {
                //jedisPool.returnResource(jedis); //该方法过时
                jedis.close();
            } catch (Exception e) {
                logger.error("close redis conn fail : ", e);
            }
        }
    }
}
